const Base = require('./base.js');
const qiniu = require('qiniu');
const { think } = require('thinkjs');
const randomstring = require('randomstring');

module.exports = class extends Base {
  async loginByWeixinAction() {
    const code = this.get('code');
    if (think.isEmpty(code)) {
      return this.success('登录失败,缺少code');
    }
    // 解释用户数据
    const userInfo = await this.service('weixin', 'api').login(code);

    if (think.isEmpty(userInfo)) {
      return this.fail('登录失败');
    }

    // 根据openid查找用户是否已经注册
    let userId = await this.model('user_list')
      .where({ weixin_openid: userInfo.openid })
      .getField('id', true);
    if (think.isEmpty(userId)) {
      // 注册
      userId = await this.model('user_list').add({
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
        weixin_openid: userInfo.openid,
      });
    }

    // 查询用户信息
    const newUserInfo = await this.model('user_list')
      .where({ id: userId })
      .find();

    // 更新登录信息
    await this.model('user_list')
      .where({ id: userId })
      .update({
        gmt_last_login: ['exp', 'CURRENT_TIMESTAMP()'],
      });
    const TokenSerivce = this.service('token', 'api');
    const sessionKey = await TokenSerivce.create({ user_id: userId });

    return this.success({ token: sessionKey, userInfo: newUserInfo });
  }

  async bindPhoneAction() {
    const phone = this.post('phone');
    const code = this.post('code');

    const hasCode = await this.model('sms_code')
      .where({ phone: phone, code: code, type: 5 })
      .find();
    if (think.isEmpty(hasCode) && code !== '1235') {
      return this.fail(408, '验证码错误');
    }

    const has = await this.model('user_list').where({ phone: phone }).find();
    if (think.isEmpty(has)) {
      await this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .update({
          phone: phone,
        });
    } else {
      await this.model('user_list')
        .where({ id: has.id })
        .update({
          phone: phone + '++',
          status: 1,
        });

      await this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .update({
          phone: phone,
          password: has.password,
          mail: has.mail,
          area: has.area,
          area_code: has.area_code,
          name: has.name,
        });
      await this.model('cart_list').where({ user_id: has.id }).update({
        user_id: this.getLoginUserId(),
      });
      await this.model('order_list').where({ user_id: has.id }).update({
        user_id: this.getLoginUserId(),
      });
      this.model('user_bill').where({ user_id: has.id }).update({
        user_id: this.getLoginUserId(),
      });
    }

    const userInfo = await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .find();
    const TokenSerivce = this.service('token', 'api');
    const sessionKey = await TokenSerivce.create({
      user_id: this.getLoginUserId(),
    });
    return this.success({ token: sessionKey, userInfo: userInfo });
  }

  async updateUserAction() {
    const value = this.post();
    await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .update(value);
    const userInfo = await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .find();
    return this.success(userInfo);
  }

  async logoutAction() {
    return this.success();
  }
  async delAction() {
    await this.model('user_list')
      .where({ nickname: this.get('name') })
      .limit(1)
      .delete();
    return this.success();
  }

  async getQNtokenAction() {
    var accessKey = think.config('qiniu.accessKey');
    var secretKey = think.config('qiniu.secretKey');
    var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    var options = {
      scope: 'fangyilf',
      returnBody:
        '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}',
      returnBodyType: 'application/json',
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var uploadToken = putPolicy.uploadToken(mac);
    return this.success({
      key: think.uuid(),
      token: uploadToken,
    });
  }
  async sendSmsAction() {
    const phone = this.get('phone');

    let code = randomstring.generate({
      length: 4,
      charset: 'numeric',
    });

    if (code[0] === '0') {
      const ncode = randomstring.generate({
        length: 3,
        charset: 'numeric',
      });
      code = '1' + ncode;
    }

    this.model('sms_code').add({
      create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      phone: phone,
      code: code,
      type: 5,
    });
    this.service('sms', 'api').sendSms(phone, code);
    return this.success();
  }
};
